/*
 * @Author: diana
 * @Date: 2023-05-05 21:52:34
 * @LastEditTime: 2023-05-06 19:50:35
 */
import React, { useEffect, useState } from "react";
import { ethers } from "ethers";

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import abi from "./CoffeeSeller.json";
import { Box, Button, ButtonGroup, Divider, Heading, Input, Stack,Text, Textarea } from "@chakra-ui/react";
import {
  Accordion,
  AccordionItem,
  AccordionButton,
  AccordionPanel,
  AccordionIcon,
} from '@chakra-ui/react'
declare let window: any;
function App() {
  // 合约地址abi
  const contractAddress = "0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9";
  //合约编译的json文件
  const contractABI = abi.abi;
  const toatTime = 2
  // 接收参数
  const [currentAccount, setCurrentAccount] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");

  const [allCoffee, setAllCoffee] = useState([]);

  // 检查是否连接钱包
  const checkIfWalletIsConnected = async () => {
    try {
      //window.ethereum
      const { ethereum } = window;
      // 获取当前网页连接的账户
      const accounts = await ethereum.request({ method: "eth_accounts" });

      if (accounts.length !== 0) {
        const currentAc = accounts[0];
        setCurrentAccount(currentAc);

        toast.success("Wallet is Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      } else {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      }
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  // 连接钱包
  const connectWallet = async () => {
    try {
      const { ethereum } = window;
      if (!ethereum) {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
        return;
      }
      // 申请连接，弹窗
      const account = ethereum.request({ method: "eth_requestAccounts" });
      setCurrentAccount(account[0]);
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

 

  // 获取已购买的数组以便展示
  const getAllCoffee = async () => {
    try {
      const { ethereum } = window;
      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const coffeeContract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );
        console.log("获取咖啡");
        const coffees = await coffeeContract.getCoffees();

        const finalCoffees = coffees.map((item) => {
          return {
            address: item.giver,
            name: item.name,
            message: item.message,
            timestamp: new Date(item.timestamp * 1000),
          };
        });
        console.log(finalCoffees);
        setAllCoffee(finalCoffees);

        console.log("------------#---------------", finalCoffees);
      } else {
        console.log("Ethereum object doesn't exist!");
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    let coffeeContract;
    checkIfWalletIsConnected();

    getAllCoffee();

    // 监听时调用的函数
    const onNewCoffee = (from, name, message, timestamp) => {
      setAllCoffee((pre) => [
        ...pre,
        {
          address: from,
          name: name,
          message: message,
          timestamp: new Date(timestamp * 1000),
        },
      ]);
    };

    if (window.ethereum) {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();

      coffeeContract = new ethers.Contract(
        contractAddress,
        contractABI,
        signer
      );
      coffeeContract.on("NewCoffee", onNewCoffee);
    }

    return () => {
      // 关闭订阅的监听
      if (coffeeContract) {
        coffeeContract.off("NewCoffee", onNewCoffee);
      }
    };
  }, []);

  // 输入框值变化事件
  const handleOnMessageChange = (e) => {
    const { value } = e.target;
    setMessage(value);
  };
  const handleOnNameChange = (e) => {
    const { value } = e.target;
    setName(value);
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-1 bg-gray-100">
      <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
       

      
         <Heading>Your Orders</Heading>
  <Accordion>
        {allCoffee.map((coffee, index) => {
          return (
           
          
            <AccordionItem>
              <h2>
                <AccordionButton>
                  <Box as="span" flex='1' textAlign='left'>
                  {coffee.name}
                  </Box>
                  <AccordionIcon />
                </AccordionButton>
              </h2>
              <AccordionPanel pb={4}>
               <Text>coffeeName: {coffee.name}</Text>
               <Text>Message: {coffee.message}</Text>
              </AccordionPanel>
            </AccordionItem>

           
          );
        })}
 </Accordion>
        <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
        />
      </main>
    </div>
  );
}

export default App;
